from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import unittest, time


class FilmAdding (unittest.TestCase):

  def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(30)
    self.driver.base_url = "http://localhost"
    self.verificationErrors = []
    self.accept_next_alert = True

  def test_Happy_path (self):
    driver = self.driver
    driver.get(driver.base_url + "/php4dvd")
    for name in ["username", "password"]:
      credential = driver.find_element_by_name(name)
      credential.send_keys(Keys.CONTROL, "a",Keys.DELETE)
      time.sleep(1)
      credential.send_keys("admin")
      credential.send_keys(Keys.RETURN)
    add_button = driver.find_element_by_xpath("//li[1]/div/div/a")
    add_button.click()
    time.sleep(2)
    imdb_number = driver.find_element_by_xpath("//tr[1]/td[2]/input")
    add_from_imdb = driver.find_element_by_id("imdbsearch")
    field_title = driver.find_element_by_xpath("//tr[2]/td[2]/input")
    field_year = driver.find_element_by_xpath("//tr[4]/td[2]/input")
    radio_own_movie_yes = driver.find_element_by_id("own_yes")
    radio_own_movie_no = driver.find_element_by_id("own_no")
    radio_seen_no = driver.find_element_by_id("seen_no")
    radio_seen_yes = driver.find_element_by_id("seen_yes")
    button_submit = driver.find_element_by_id("submit")
    add_from_imdb.send_keys(Keys.CONTROL, "a")
    add_from_imdb.send_keys(Keys.DELETE)
    add_from_imdb.send_keys("Oblivion")
    imdb_number.send_keys(Keys.CONTROL, "a")
    imdb_number.send_keys(Keys.DELETE)
    imdb_number.send_keys("1")
    field_title.send_keys(Keys.CONTROL, "a")
    field_title.send_keys(Keys.DELETE)
    field_title.send_keys("Oblivion")
    field_year.send_keys(Keys.CONTROL, "a")
    field_year.send_keys(Keys.DELETE)
    field_year.send_keys("2013")
    radio_own_movie_yes.click()
    radio_seen_no.click()
    button_submit.click()
    time.sleep(5)
    driver.get_screenshot_as_file("filmadding.png")
    time.sleep(20)


  def is_element_present(self, how, what):
    try: self.driver.find_element(by=how, value=what)
    except NoSuchElementException, e: return False
    return True

  def close_alert_and_get_its_text(self):
    try:
      alert = self.driver.switch_to_alert()
      if self.accept_next_alert:
        alert.accept()
      else:
        alert.dismiss()
      return alert.text
    finally: self.accept_next_alert = True



  def tearDown (self):
    self.driver.quit()


if __name__ == "__main__":
  unittest.main()
